package com.nova.bluetooth.permission;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.nova.bluetooth.base.BaseActivity;


import java.util.List;

public class PermissionManageActivity extends BaseActivity {
    private boolean isShowingGPSDialog = false;
    private boolean isShowingEnableBtDialog = false;
    private ActivityResultLauncher<Intent> enableBtIntentResultLauncher;
    private ActivityResultLauncher<Intent> locationIntentResultLauncher;

    private OnPermissionListener mOnPermissionListener;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        locationIntentResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    isShowingGPSDialog = false;
                    if (checkGPSIsOpen()) {
                        requestPermissions(PermissionType.LOCATION);
                    }
                });

        enableBtIntentResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    isShowingEnableBtDialog = false;
                    if (checkBluetoothIsOpen()) {
                        requestPermissions(PermissionType.BLUETOOTH);
                    }
                });
    }


    /*******************************外部方法********************************/
    public void getBluetoothPermission(OnPermissionListener listener, String message) {
        mOnPermissionListener = listener;
        if (checkPermissions(PermissionType.LOCATION) && checkGPSIsOpen()) {
            if (checkPermissions(PermissionType.BLUETOOTH) && checkBluetoothIsOpen()) {
                if (mOnPermissionListener != null) {
                    mOnPermissionListener.onPermissionGranted(PermissionType.BLUETOOTH);
                }
            } else {
                requestPermissions(PermissionType.BLUETOOTH);
            }

        } else {
            requestPermissions(PermissionType.LOCATION);
        }

    }

    public void getRecordAudioPermission(OnPermissionListener listener, String message) {
        mOnPermissionListener = listener;
        if (checkPermissions(PermissionType.RECORD_AUDIO)) {
            if (mOnPermissionListener != null) {
                mOnPermissionListener.onPermissionGranted(PermissionType.RECORD_AUDIO);
            }
        } else {
            requestPermissions(PermissionType.RECORD_AUDIO);
        }
    }

    public void getManageExternalStoragePermission(OnPermissionListener listener, String message) {
        mOnPermissionListener = listener;
        if (checkPermissions(PermissionType.EXTERNAL_STORAGE)) {
            if (mOnPermissionListener != null) {
                mOnPermissionListener.onPermissionGranted(PermissionType.EXTERNAL_STORAGE);
            }
        } else {
            requestPermissions(PermissionType.EXTERNAL_STORAGE);
        }
    }

    public void getReadMediaPermission(OnPermissionListener listener, String message) {
        mOnPermissionListener = listener;
        if (checkPermissions(PermissionType.READ_MEDIA)) {
            if (mOnPermissionListener != null) {
                mOnPermissionListener.onPermissionGranted(PermissionType.READ_MEDIA);
            }
        } else {
            requestPermissions(PermissionType.READ_MEDIA);
        }
    }

    public void getCameraPermission(OnPermissionListener listener, String message) {
        mOnPermissionListener = listener;
        if (checkPermissions(PermissionType.CAMERA)) {
            if (mOnPermissionListener != null) {
                mOnPermissionListener.onPermissionGranted(PermissionType.CAMERA);
            }
        } else {
            requestPermissions(PermissionType.CAMERA);
        }
    }

    public void getAIUIRecordPermission(OnPermissionListener listener, String message) {
        mOnPermissionListener = listener;
        if (checkPermissions(PermissionType.AIUI_RECORD)) {
            if (mOnPermissionListener != null) {
                mOnPermissionListener.onPermissionGranted(PermissionType.AIUI_RECORD);
            }
        } else {
            requestPermissions(PermissionType.AIUI_RECORD);
        }
    }

    public void getMediaAudioPermission(OnPermissionListener listener, String message) {
        mOnPermissionListener = listener;
        if (checkPermissions(PermissionType.MEDIA_AUDIO)) {
            if (mOnPermissionListener != null) {
                mOnPermissionListener.onPermissionGranted(PermissionType.MEDIA_AUDIO);
            }
        } else {
            requestPermissions(PermissionType.MEDIA_AUDIO);
        }
    }

    /********************************内部方法******************************/

    private boolean checkPermissions(PermissionType permissionType) {
        switch (permissionType) {
            case LOCATION:
                return XXPermissions.isGranted(
                        this,
                        Permission.ACCESS_FINE_LOCATION,
                        Permission.ACCESS_COARSE_LOCATION);
            case BLUETOOTH:
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
                    return XXPermissions.isGranted(
                            this,
                            Permission.BLUETOOTH_SCAN,
                            Permission.BLUETOOTH_CONNECT,
                            Permission.BLUETOOTH_ADVERTISE,
                            Permission.ACCESS_FINE_LOCATION,
                            Permission.ACCESS_COARSE_LOCATION);
                } else {
                    return XXPermissions.isGranted(
                            this,
                            Permission.ACCESS_FINE_LOCATION,
                            Permission.ACCESS_COARSE_LOCATION);
                }
            case RECORD_AUDIO:
                return XXPermissions.isGranted(
                        this,
                        Permission.RECORD_AUDIO);
            case EXTERNAL_STORAGE:
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                    return XXPermissions.isGranted(
                            this,
                            Permission.READ_MEDIA_IMAGES,
                            Permission.READ_MEDIA_AUDIO);
                }else {
                    return XXPermissions.isGranted(
                            this,
                            Permission.WRITE_EXTERNAL_STORAGE,
                            Permission.READ_EXTERNAL_STORAGE);
                }
            case READ_MEDIA:
                return XXPermissions.isGranted(
                        this,
                        Permission.READ_MEDIA_IMAGES
                );
            case CAMERA:
                return XXPermissions.isGranted(
                        this,
                        Permission.CAMERA);
            case AIUI_RECORD:
                return XXPermissions.isGranted(
                        this,
                        Permission.READ_PHONE_STATE,
                        Permission.RECORD_AUDIO);
            case MEDIA_AUDIO:
                return XXPermissions.isGranted(
                        this,
                        Permission.READ_MEDIA_AUDIO);
        }
        return false;
    }

    private void requestPermissions(PermissionType permissionType) {
        switch (permissionType) {
            case LOCATION:
                if (checkGPSIsOpen()) {
                    XXPermissions.with(this)
                            .permission(Permission.ACCESS_FINE_LOCATION)
                            .permission(Permission.ACCESS_COARSE_LOCATION)
                            .request(doOnPermissionCallback(permissionType));
                } else {
                    openGps();
                }
                break;
            case BLUETOOTH:
                XXPermissions.with(this)
                        .permission(Permission.BLUETOOTH_SCAN)
                        .permission(Permission.BLUETOOTH_CONNECT)
                        .permission(Permission.BLUETOOTH_ADVERTISE)
                        .permission(Permission.ACCESS_FINE_LOCATION)
                        .permission(Permission.ACCESS_COARSE_LOCATION)
                        .request(doOnPermissionCallback(permissionType));
                break;
            case RECORD_AUDIO:
                XXPermissions.with(this)
                        .permission(Permission.RECORD_AUDIO)
                        .request(doOnPermissionCallback(permissionType));
                break;
            case READ_MEDIA:
                XXPermissions.with(this)
                        .permission(Permission.READ_MEDIA_IMAGES)
//                        .permission(Permission.READ_MEDIA_AUDIO)
                        .request(doOnPermissionCallback(permissionType));
                break;
            case CAMERA:
                XXPermissions.with(this)
                        .permission(Permission.CAMERA)
                        .request(doOnPermissionCallback(permissionType));
                break;
            case AIUI_RECORD:
                XXPermissions.with(this)
                        .permission(Permission.READ_PHONE_STATE)
                        .permission(Permission.RECORD_AUDIO)
                        .request(doOnPermissionCallback(permissionType));
                break;
            case EXTERNAL_STORAGE:
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
                    XXPermissions.with(this)
                            .permission(Permission.READ_MEDIA_IMAGES)
                            .permission(Permission.READ_MEDIA_AUDIO)
                            .request(doOnPermissionCallback(permissionType));
                }else {
                    XXPermissions.with(this)
                            .permission(Permission.READ_EXTERNAL_STORAGE)
                            .permission(Permission.WRITE_EXTERNAL_STORAGE)
                            .request(doOnPermissionCallback(permissionType));
                }
                break;
            case MEDIA_AUDIO:
                XXPermissions.with(this)
                        .permission(Permission.READ_MEDIA_AUDIO)
                        .request(doOnPermissionCallback(permissionType));
                break;
        }
    }

    private OnPermissionCallback doOnPermissionCallback(PermissionType permissionType) {
        return new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                if (all) {
                    if (mOnPermissionListener != null) {
                        if (permissionType == PermissionType.LOCATION) {
                            requestPermissions(PermissionType.BLUETOOTH);
                        } else if (permissionType == PermissionType.BLUETOOTH) {
                            if (checkBluetoothIsOpen()) {
                                mOnPermissionListener.onPermissionGranted(permissionType);
                            } else { //要先有蓝牙权限再去打开蓝牙开关，不然会闪退
                                openBluetooth();
                            }
                        } else {
                            mOnPermissionListener.onPermissionGranted(permissionType);
                        }
                    }
                }
            }

            @Override
            public void onDenied(List<String> perissions, boolean never) {
                if (mOnPermissionListener != null) {
                    mOnPermissionListener.onPermissionDenied(permissionType);
                }

                if (never) {
                    PermissionPageManagement.goToSetting(PermissionManageActivity.this);
                }
            }
        };
    }


    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    private boolean checkBluetoothIsOpen() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null)
            return false;

        return bluetoothAdapter.isEnabled();
    }

    private void openGps() {
        if (!isShowingGPSDialog && !isDestroyed()) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            locationIntentResultLauncher.launch(intent);
            isShowingGPSDialog = true;
        }
    }

    @SuppressLint("MissingPermission")
    private void openBluetooth() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null)
            return;

        if (!bluetoothAdapter.isEnabled() && !isShowingEnableBtDialog && !isDestroyed()) {
            isShowingEnableBtDialog = true;
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBtIntentResultLauncher.launch(enableBtIntent);
        }
    }
}
